package core

import (
	"fmt"
	"gopkg.in/yaml.v2"
	"io/ioutil"
	"os"
	"strconv"
)

var bootConfig BootConfig

func loadConfig() {
	configFile, err := ioutil.ReadFile("conf/application.yml")
	if err != nil {
		Logger().Fatalf("yamlFile.Get err %v ", err)
		return
	}
	err = yaml.Unmarshal(configFile, &bootConfig)
	if err != nil {
		Logger().Fatalf("yamlFile.parse err %v ", err)
		return
	}
}

/**
获取服务监听地址
*/
func ListenAddr() string {
	port := bootConfig.Server.Port
	if port <= 0 {
		port, _ = strconv.Atoi(os.Getenv("PORT"))
		if port <= 0 {
			port = 8080
		}
	}
	return fmt.Sprintf(":%d", port)
}

func GetAppConfig() *AppInfo {
	return &bootConfig.AppInfo
}

func GetServerConfig() *ServerInfo {
	return &bootConfig.Server
}

func GetAppName() string {
	return bootConfig.AppInfo.Name
}

//
func GetDatasouce() *Datasource {
	return &bootConfig.Datasource
}

type BootConfig struct {
	AppInfo    AppInfo    `yaml:"app"`
	Server     ServerInfo `yaml:"server"`
	Datasource Datasource `yaml:"datasource"`
}

type AppInfo struct {
	Name       string `yaml:"name"`
	Debug      bool   `yaml:"debug"`
	CssVersion string `yaml:"cssversion"`
}

type ServerInfo struct {
	Port            int    `yaml:"port"`
	SessionCookieId string `yaml:"cookieid"`
	SessionExpires  int    `yaml:"sessionexpires"` //过期时间，分钟
}

type Datasource struct {
	Username string `yaml:"uid"`
	Password string `yaml:"pwd"`
	Host     string `yaml:"host"`
	Database string `yaml:"database"`
	Port     int    `yaml:"port"`
}
